//
//  OfficeScheduledViewController.swift
//  EduManage
//
//  Created by design02 on 16/12/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class OfficeScheduledViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

    
    var segmentedControl = UISegmentedControl()
    
    var tableView = UITableView()
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    
    var chart = PDChart()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "工作安排"
        
        setupViews()

    }
    
    func setupViews(){
        
        let array = ["柱状图","折线图"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 15, y: 74, width: screenW - 30, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(OfficeScheduledViewController.refresh), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)

        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
  
        tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(OfficeScheduledViewController.refresh))
        tableView.footer = nil
        tableView.header.beginRefreshing()
    }
   
    /**
     刷新数据
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            
            /**
             1）统计发布数量接口地址：GJ_ModularmentBG.ashx?t=4
             2）统计发布数量参数：
             XmlNode schidxml = ndoc.SelectSingleNode("//rss/channel/schid");
             */
            
            let user = getUserPojo()
            let url = server + adminofficewebappapi
            let request = requestHeader + "4</t><schid>" + user.schid + "</schid></channel></rss>"
            
            workArray = getData(url, request: request)
            
            tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            let currentSegment = self.segmentedControl.selectedSegmentIndex
            
            if currentSegment == 0 {
                self.chart.removeFromSuperview()
                if !self.tableView.subviews.contains(chart) {
                    let barChart: PDBarChart = self.getBarChart(workArray)
                    chart = barChart
                    self.tableView.addSubview(chart)
                }
                chart.strokeChart()
                print("显示柱状图")
                
            }else if currentSegment == 1 {
                self.chart.removeFromSuperview()
                if !self.tableView.subviews.contains(chart) {
                    let barChart: PDLineChart = self.getLineChart(workArray)
                    chart = barChart
                    self.tableView.addSubview(chart)
                }
                chart.strokeChart()
                print("显示折线图")
                
            }
            tableView.reloadData()
            
        } else {
            let alert = UIAlertView.init(title: "错误提示", message: "似乎已断开与互联网的连接", delegate: nil, cancelButtonTitle: "知道了")
            alert.show()
            
            self.perform(#selector(OfficeScheduledViewController.dimissAlert(alert:)), with: alert, afterDelay: 2.0)
           
            HYLog("网络连接：不可用")
        }
        
        tableView.header.endRefreshing()
    }
  
    func dimissAlert(alert: UIAlertView) {
        alert.dismiss(withClickedButtonIndex: alert.cancelButtonIndex, animated: true)
    }
    //MARK: - ui table view delegate and data source

    func numberOfSections(in tableView: UITableView) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellIdentifier = "OfficeClassSendTableViewCellIdentifier";
        
        let cell: UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
        cell.selectionStyle = UITableViewCellSelectionStyle.none;
        if (indexPath as NSIndexPath).row < workArray.count {
            
            let dic = workArray[indexPath.row] as! JSON
            let mMonth = dic["mMonth"].stringValue
            let csnum = dic["csnum"].stringValue
            let StartDate = dic["StartDate"].stringValue
            let EndDate = dic["EndDate"].stringValue
            print("\(mMonth)月份、发布了\(csnum)条、\(StartDate.components(separatedBy: " ").first!)-\(EndDate.components(separatedBy: " ").first!)")
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    // row 的 行高
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 0
    }
    
    //MARK: - 设计图表 - 柱状图
    
    func getBarChart(_ array: NSMutableArray) -> PDBarChart {
        
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...array.count-1 {
            let tempNumber = (array[i] as! JSON)["csnum"].intValue
            let temgmMonth = (array[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (array[i] as! JSON)["mMonth"].intValue, y: (array[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }
        
        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat(10.0)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        
        let dataItem: PDBarChartDataItem = PDBarChartDataItem()
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        dataItem.barPointArray = tempPointArr
        dataItem.xAxesDegreeTexts = tempMouthArr
        
        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        let frameW = self.view.frame.size.width
        let barChart: PDBarChart = PDBarChart(frame: CGRect(x: 15, y: 10, width: frameW-30, height: frameW*3.2/4), dataItem: dataItem)
        return barChart
    }
    
    //MARK: - 折线图
    func getLineChart(_ array: NSMutableArray) -> PDLineChart {
        
        let tempArr = NSMutableArray()
        var tempPointArr: [CGPoint]?
        var tempMouthArr: [String]?
        
        tempPointArr = [CGPoint]()
        tempMouthArr = [String]()
        
        for i in 0...array.count-1 {
            let tempNumber = (array[i] as! JSON)["csnum"].intValue
            let temgmMonth = (array[i] as! JSON)["mMonth"].intValue
            let tempPoint:CGPoint = CGPoint(x: (array[i] as! JSON)["mMonth"].intValue, y: (array[i] as! JSON)["csnum"].intValue)
            
            tempArr.add(tempNumber)
            tempPointArr?.append(tempPoint)
            tempMouthArr?.append("\(temgmMonth)月")
            
        }
        
        
        let m = tempArr.value(forKeyPath: "@max.intValue")! as! Int
        var ymax = CGFloat(0.0)
        var yinterval = CGFloat(0.0)
        
        if (m < 10) {
            ymax = CGFloat(10.0)
            yinterval = 1.0
            
        }else if (m > 10 && m < 100) {
            ymax = CGFloat((m/10+1)*10)
            yinterval = 10.0
            
        }else if (m > 100 && m < 1000) {
            ymax = CGFloat((m/100+1)*10)
            yinterval = 100.0
            
        }else {
            ymax = CGFloat((m/1000+1)*10)
            yinterval = 1000.0
        }
        
        let dataItem: PDLineChartDataItem = PDLineChartDataItem()
        dataItem.xMax = CGFloat((tempMouthArr?.count)!)
        dataItem.xInterval = 1.0
        dataItem.yMax = ymax
        dataItem.yInterval = yinterval
        
        dataItem.pointArray = tempPointArr
        dataItem.xAxesDegreeTexts = tempMouthArr
        //        dataItem.yAxesDegreeTexts = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
        
        
        let frameW = self.view.frame.size.width
        let lineChart: PDLineChart = PDLineChart(frame: CGRect(x: 15, y: 10, width: frameW-30, height: frameW*3.2/4), dataItem: dataItem)
        return lineChart
    }    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
